<template>
  <div class="login-form">
    <img class="form-img2" :src="FormImg2" alt="" />
    <div class="form">
      <p class="title">南城县智慧停车一体化平台</p>
      <div class="form-content">
        <div class="qrCodes">
          <div></div>
          <div class="qrCode-img">
            <div class="qrCode" v-if="QRCodeFlag">
              扫码登录安全快捷
              <div class="el-icon-right"></div>
            </div>
            <div class="form-img3" @click="generateQRCode" v-if="QRCodeFlag == true">
              <img :src="FormImg3" alt="" />
            </div>
            <div class="form-img3" @click="generateQRCode" v-if="QRCodeFlag == false">
              <img :src="FormImg4" alt="" />
            </div>
          </div>
        </div>

        <div class="options" v-if="QRCodeFlag">
          <div
            v-for="item in options"
            :key="item.id"
            :class="{ 'option-item': true, selected: item.selected }"
            @click="selectOption(item.id)"
          >
            {{ item.label }}
            <!-- <el-divider direction="vertical" /> -->
          </div>
        </div>
      </div>

      <div v-if="QRCodeFlag" class="form-content2">
        <el-form
          :model="form"
          class="model"
          :rules="rules"
          ref="formRef"
          v-if="optionsValue === 0"
        >
          <div v-if="nonEmpty" class="noEmpty">{{ nonError }}</div>
          <el-form-item prop="account">
            <el-input
              :prefix-icon="User"
              v-model="form.account"
              placeholder="请输入账号"
              style="width: 320px; height: 40px"
              @keyup.enter="handleLogin"
            />
          </el-form-item>
          <el-form-item class="pwd-input" prop="pwd">
            <el-input
              type="password"
              :prefix-icon="Lock"
              v-model="form.pwd"
              placeholder="请输入密码"
              style="width: 320px; height: 40px"
              @keyup.enter="handleLogin"
            />
          </el-form-item>
          <el-form-item prop="checkcode">
            <div class="checkcodes">
              <el-input
                v-model="form.checkcode"
                placeholder="请输入验证码"
                style="width: 190px; height: 40px"
                @keyup.enter="handleLogin"
              ></el-input>
              <img :src="checkcodeImg" class="checkcodeImg" alt="" @click="init" />
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="login-btn" @click="handleLogin">
              登录
            </el-button>
          </el-form-item>
        </el-form>
        <el-form
          :model="form2"
          class="model"
          :rules="rules2"
          ref="formRef2"
          v-if="optionsValue === 1"
        >
          <div v-if="userFlag" class="noEmpty">{{ userError }}</div>
          <el-form-item prop="phone" class="phone-input">
            <el-input
              v-model="form2.phone"
              placeholder="请输入手机号"
              style="width: 320px; height: 40px"
            >
              <template #prepend>+86</template>
            </el-input>
          </el-form-item>
          <el-form-item class="pwd-input code-input" prop="code">
            <el-input
              v-model="form2.code"
              placeholder="请输入验证码"
              style="width: 320px; height: 40px"
            >
              <template #append>
                <el-button @click="getCodeData">
                  <div v-if="verificationCode == '获取验证码'">
                    {{ verificationCode }}
                  </div>
                  <div v-else-if="verificationCode == '重新获取'" class="code-blue">
                    {{ verificationCode }}
                  </div>
                  <div v-else class="code-blue">{{ verificationCode }}秒后重新获取</div>
                </el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="login-btn" @click="handleLogin2">
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="login-form-qrCode" v-if="QRCodeFlag == false">
        <div class="login-form-qrCode-img">
          <article id="loginQrcode" class="loginQrcode"></article>
          <div class="login-form-qrCode-invalid" v-if="verificationCode2 === '请重试'">
            <p>已失效</p>
            <el-button @click="getQRCodeInvalid">点击重试</el-button>
          </div>
          <div v-if="RedirectFlag" class="login-form-qrCode-invalid">
            <p>您未绑定任何账号</p>
            <el-button @click="getQRCodeInvalid">点击重试</el-button>
          </div>
        </div>

        <p>使用微信扫一扫登录</p>
        <!-- {{ verificationCode2 }} -->
      </div>
    </div>
  </div>
</template>

<script setup>
import FormImg2 from "../../../assets/image/login/form_img.png";
import FormImg3 from "../../../assets/image/login/qr_code.png";
import FormImg4 from "../../../assets/image/login/qr_code2.png";
import { User, Lock } from "@element-plus/icons-vue";
import { reactive, ref, nextTick } from "vue";
import useMenuStore from "../../../store/modules/menu.js";
import useUserStore from "../../../store/modules/user";
import {
  login,
  getUserPhone,
  getCode,
  system,
  getRefresh,
  getCheckcode,
  getRoutesApi,
} from "../../../service/modules/user";
import { encrypt } from "../../../utils/crypto";
import { useRouter } from "vue-router";

const router = useRouter();
const menuStore = useMenuStore();
const nonError = ref("");
const userStore = useUserStore();

const nonEmpty = ref(false);

const options = ref([
  {
    id: 0,
    label: "密码登录",
    selected: true,
  },
  {
    id: 1,
    label: "短信登录",
    selected: false,
  },
]);

const optionsValue = ref(0);
const selectOption = (id) => {
  nonEmpty.value = false;
  options.value.forEach((item) => {
    if (item.id === id) {
      item.selected = true;
      optionsValue.value = id;
    } else {
      item.selected = false;
    }
  });
};

const getQRCodeInvalid = () => {
  RedirectFlag.value = false;
  generateQRCode2();
};
const generateQRCode2 = () => {
  // QRCodeFlag.value = !QRCodeFlag.value;

  nextTick(generateWxQRCode);
};

const QRCodeFlag = ref(true);
const generateQRCode = () => {
  QRCodeFlag.value = !QRCodeFlag.value;

  !QRCodeFlag.value && nextTick(generateWxQRCode);
};

// 二维码验证
const userSystem = ref("cipp_wx_web_appId");
const verificationCode2 = ref("");
function generateWxQRCode() {
  system(userSystem.value).then((res) => {
    if (res.data.code == 0) {
      const res2 = new WxLogin({
        self_redirect: false,
        id: "loginQrcode",
        appid: res.data.result.value,
        scope: "snsapi_login",
        redirect_uri:
          "https%3A%2F%2Fcipp.ecaray.com%2Fuser%2FwxLogin%2Fauthorize%2Fcallback",
        state: "",
        style: "",
        href: "",
      });
      // console.log(res2, "二维码");
      verificationCode2.value = 60;
      let timer = setInterval(() => {
        verificationCode2.value--;
        if (verificationCode2.value === 0) {
          clearInterval(timer);
          verificationCode2.value = "请重试";
        }
      }, 1000);
    }
  });
}

function parseURLParams(url) {
  // 获取 URL 中的参数部分
  const paramStartIndex = url.indexOf("?");
  if (paramStartIndex === -1) {
    console.error("URL中没有参数");
    return;
  }
  const paramString = url.substring(paramStartIndex + 1);

  // 解析参数字符串为对象
  const urlParams = new URLSearchParams(paramString);

  // 创建一个对象来存储参数
  const params = {};

  // 遍历 URLSearchParams 对象，将参数存储到对象中
  for (const [key, value] of urlParams) {
    params[key] = value;
  }

  return params;
}

const checkcodeImg = ref("");
const init = async () => {
  await getCheckcode({
    checkCodeType: "math",
  })
    .then((res) => {
      console.log("res ===>", res);
      checkcodeImg.value = res.data.result.aliasing;
      form.checkcodekey = res.data.result.key;
    })
    .catch((err) => {
      console.log("err ===>", err);
    });
};

init();

const getDate = async (res) => {
  setTimeout(async () => {
    await getRefresh({
      client_id: "CippWebApp",
      client_secret: "CippWebApp",
      grant_type: "refresh_token",
      refresh_token: res.data.refresh_token,
    }).then(async (response) => {
      // console.log("无感刷新token ===>", response);
      if (response.data.scope == "all") {
        userStore.setInfo(response.data);
        userStore.setToken(response.data.access_token);
        await getDate(response);
      }
    });
  }, 3600000);

  // // 创建一个表示当前时间的Date对象
  // const currentDate = new Date();

  // // 获取当前时间的时间戳（单位：毫秒）
  // const currentTimestamp = currentDate.getTime();

  // // 将秒数转换为毫秒数
  // const secondsToAdd = res.data.expires_in;
  // const millisecondsToAdd = secondsToAdd * 1000;

  // // 计算加上秒数后的时间戳
  // const newTimestamp = currentTimestamp + millisecondsToAdd;

  // // 创建一个新的Date对象，表示加上秒数后的时间
  // const newDate = new Date(newTimestamp);
  // console.log("newDate ===>", newDate.getTime());

  // localStorage.setItem("newDate", newDate.getTime());
  // // 检查是否当前时间与加上秒数后的时间相同
  // if (currentDate.getTime() === newDate.getTime()) {
  //   console.log("当前时间与当前时间加上7199秒相同！");
  // } else {
  //   console.log("当前时间与当前时间加上7199秒不同！");
  // }
};

// userid=83768b2a06cc11efbcae408d5ccfd315&username=t1&authType=wx
const RedirectFlag = ref(false);
async function handleWxLoginRedirect() {
  // 获取当前页面的 URL
  const currentUrl = window.location.hash;
  const params = parseURLParams(currentUrl);
  console.log("params ===>", params);
  if (params != undefined) {
    if (params.hasOwnProperty("userid")) {
      const username = {
        userid: params.userid,
        // username: params.username,
        authType: params.authType,
        userType: "sys",
      };
      const usernameStr = JSON.stringify(username);

      const res = await login({
        client_id: "CippWebApp",
        client_secret: "CippWebApp",
        grant_type: "password",
        username: usernameStr,
      });
      // console.log(res, "res");
      if (res.data.scope == "all") {
        // nonEmpty.value = false;
        userStore.setInfo(res.data);
        userStore.setToken(res.data.access_token);
        await getDate(res);
        await getRoutesApi().then((res) => {
          console.log(res);
          menuStore.setMenu(res.data.result);
        });
        router.push("/work");
      } else {
        // nonEmpty.value = true;
        // nonError.value = res.data.error_description;
      }
      // 执行相应操作
    } else {
      console.error("URL参数不正确，缺少userid");
      // 执行其他操作或报错处理
      RedirectFlag.value = true;
      QRCodeFlag.value = false;
    }
  }

  //   if (!params) return;

  //   // 检查参数中是否包含 userid
  //   if (params.hasOwnProperty("userid")) {
  //     const userid = params["userid"];
  //     console.log("User ID:", userid);
  //     // 执行相应操作
  //   } else {
  //     console.error("URL参数不正确，缺少userid");
  //     // 执行其他操作或报错处理
  //   }

  //   // 检查参数中是否包含 username
  //   if (params.hasOwnProperty("username")) {
  //     const username = params["username"];
  //     console.log("Username:", username);
  //     // 执行相应操作
  //   } else {
  //     console.error("URL参数不正确，缺少username");
  //     // 执行其他操作或报错处理
  //   }

  //   // 检查参数中是否包含 authType
  //   if (params.hasOwnProperty("authType")) {
  //     const authType = params["authType"];
  //     console.log("Authentication Type:", authType);
  //     // 执行相应操作
  //   } else {
  //     console.error("URL参数不正确，缺少authType");
  //     // 执行其他操作或报错处理
  //   }
}
handleWxLoginRedirect();

// 账号密码验证
const form = reactive({
  account: "",
  pwd: "",
  checkcode: "",
  checkcodekey: "",
});
const formRef = ref();

const rules = {
  account: [
    {
      required: true,
      message: "请输入账号",
      trigger: "blur",
    },
  ],
  pwd: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
  ],
  checkcode: [
    {
      required: true,
      message: "请输入验证码",
      trigger: "blur",
    },
  ],
};

// 账号密码登录
const handleLogin = async () => {
  formRef.value.validate(async (err) => {
    if (err) {
      // userStore.userLogin(form);
      const username = {
        username: form.account,
        password: form.pwd,
        authType: "password",
        userType: "sys",
        checkcode: form.checkcode,
        checkcodekey: form.checkcodekey,
      };

      const usernameStr = JSON.stringify(username);

      // console.log(usernameStr);

      await login({
        client_id: "CippWebApp",
        client_secret: "CippWebApp",
        grant_type: "password",
        username: usernameStr,
      })
        .then(async (res) => {
          nonEmpty.value = false;
          userStore.setInfo(res.data);
          userStore.setToken(res.data.access_token);
          getDate(res);
          await getRoutesApi().then((res) => {
            console.log(res);
            menuStore.setMenu(res.data.result);
          });
          router.push("/work");
        })
        .catch((err) => {
          init();
          // console.log(err);
          nonEmpty.value = true;
          nonError.value = err.response.data.error_description;
        });
    }
  });
};

// 手机号验证
const form2 = reactive({
  phone: "",
  code: "",
});
const formRef2 = ref();

const rules2 = {
  phone: [
    {
      required: true,
      message: "请输入手机号",
      trigger: "change",
    },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "手机号码格式不正确，请重新输入",
      trigger: "blur",
    },
  ],
  code: [
    {
      required: true,
      message: "请输入验证码",
      trigger: "change",
    },
  ],
};
const verificationCode = ref("获取验证码");
const userFlag = ref(false);
const userError = ref("");
const checkCodeKey = ref("");

const getCodeData = () => {
  formRef2.value.validateField("phone", (err) => {
    // console.log("err ===>", err);
    if (err) {
      if (
        verificationCode.value === "获取验证码" ||
        verificationCode.value === "重新获取"
      ) {
        console.log("form2.phone ===>", form2.phone);
        // 根据手机号判断用户是否存在
        getUserPhone(form2.phone).then((res) => {
          // console.log("res ===>", res);
          if (res.data.result) {
            userFlag.value = false;
            getCode({
              checkCodeType: "sms",
              param1: form2.phone,
            }).then((res2) => {
              checkCodeKey.value = res2.data.result.key;
            });
          } else {
            userFlag.value = true;
            userError.value = form2.phone + "不存在";
          }
        });
        verificationCode.value = 120;
        let timer = setInterval(() => {
          verificationCode.value--;
          if (verificationCode.value === 0) {
            clearInterval(timer);
            verificationCode.value = "重新获取";
          }
        }, 1000);
      }
    }
  });
};

// 手机号验证码登录
const handleLogin2 = async () => {
  // router.push("/work");
  // return;
  formRef2.value.validate(async (err) => {
    if (err) {
      // console.log("err ===>", err);

      const username = {
        cellphone: form2.phone,
        checkcode: form2.code,
        checkcodekey: checkCodeKey.value,
        authType: "sms",
        userType: "sys",
      };

      const usernameStr = JSON.stringify(username);

      // console.log(usernameStr);
      await login({
        client_id: "CippWebApp",
        client_secret: "CippWebApp",
        grant_type: "password",
        username: usernameStr,
      })
        .then(async (res) => {
          // console.log("res ===>", res);
          userFlag.value = false;
          userStore.setInfo(res.data);
          userStore.setToken(res.data.access_token);
          getDate(res);
          await getRoutesApi().then((res) => {
            console.log(res);
            menuStore.setMenu(res.data.result);
          });
          router.push("/work");
        })
        .catch((err) => {
          // console.log("res ===>", err);

          userFlag.value = true;
          userError.value = err.response.data.error_description;
        });
    }
  });
};
</script>
<style lang="less">
.login-form-qrCode {
  margin-top: -10px;
  .login-form-qrCode-img {
    overflow: hidden;
    margin: 0 auto;
    width: 164px;
    height: 164px;
    border: 1px solid #eee;
    position: relative;
    > article {
      width: 280px;
      height: 280px;
      transform: scale(0.587);
      transform-origin: left top;
      overflow: hidden;
      position: relative;
      > iframe {
        position: absolute;
        width: 300px;
        height: 400px;
        left: 50%;
        top: -47px;
        transform: translate(-50%);
      }
    }
  }
  .login-form-qrCode-invalid {
    z-index: 2;
    position: absolute;
    top: 50%;
    width: 100%;
    height: 100%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: rgba(0, 0, 0, 0.6);
    display: flex;
    align-items: center;
    flex-direction: column;
    gap: 13px;
    justify-content: center;
    > p {
      font-size: 14px;
      color: #fff;
    }
    > button {
      background: #f03a41;
      width: 88px;
      height: 30px;
      border-radius: 3px;
      color: #fff;
      font-size: 14px;
      border: 0;
    }
  }

  > p {
    margin: 0;
    font-display: 12px;
    margin-top: 10px;
    text-align: center;
    color: #666666;
  }
}
.el-input .el-input__icon {
  font-size: 24px;
}

.phone-input {
  .el-input__wrapper {
    border-right: 1px solid var(--el-border-color);
    border-top: 1px solid var(--el-border-color);
    border-bottom: 1px solid var(--el-border-color);
    box-shadow: none;
  }
}

.code-input {
  .el-input__wrapper {
    border-left: 1px solid var(--el-border-color);
    border-top: 1px solid var(--el-border-color);
    border-bottom: 1px solid var(--el-border-color);
    box-shadow: none;
  }
}
</style>
<style lang="less" scoped>
.noEmpty {
  // margin: 0 auto;
  // width: 50%;
  color: #de2910;
  font-size: 12px;
}

.login-form {
  width: 860px;
  height: 470px;
  display: flex;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0px 4px 9px 0px #e1e1e1;

  .form {
    flex: 1;
    padding: 56px 82px 37px 56px;

    .title {
      font-weight: 600;
      font-size: 28px;
      color: #333333;
      text-align: center;
      margin-bottom: 20px;
    }

    .options {
      position: absolute;
      left: 10px;
      bottom: -12px;
      display: flex;

      & > :nth-child(1) {
        margin-right: 24px;
      }
    }

    .option-item {
      cursor: pointer;
      /* 未选中状态的样式 */
      font-weight: 400;
      font-size: 16px;
      color: #666666;
      font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB",
        "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
    }

    .selected {
      font-weight: bold;
      /* 选中状态的样式 */
      font-weight: 600;
      font-size: 16px;
      color: #2986ff;
      padding-bottom: 4px;
      border-bottom: 2px solid #2986ff;
      font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB",
        "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
    }

    .model {
      margin-top: 32px;

      .pwd-input {
        margin-top: 20px;
        margin-bottom: 40px;
      }

      .checkcodes {
        width: 100%;
        display: flex;
        justify-content: space-between;
      }

      .checkcodeImg {
        width: 118px;
        height: 40px;
        border-radius: 6px;
        border: 1px solid #4fa3ff;
        cursor: pointer;
      }

      .login-btn {
        background: #409cff;
        width: 320px;
        height: 40px;
        font-weight: 500;
        font-size: 16px;
        color: #ffffff;
      }

      .code-blue {
        font-weight: 400;
        font-size: 14px;
        color: #2986ff;
      }
    }

    .form-content2 {
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }

  .form-img2 {
    flex: 1;
  }

  .form-content {
    position: relative;
    top: 0;
  }

  .qrCodes {
    display: flex;
    justify-content: space-between;

    .qrCode-img {
      display: flex;
      margin-right: 20px;
    }

    .qrCode {
      background: #a3a3a3;
      border-radius: 2px;
      width: 103px;
      height: 22px;
      line-height: 22px;
      font-weight: 400;
      font-size: 12px;
      color: #ffffff;
      text-align: center;
      margin-right: 17px;
      position: relative;
      top: 0;
    }

    .el-icon-right {
      width: 0;
      height: 0;
      border-left: 5px solid #a3a3a3;
      border-top: 5px solid transparent;
      border-bottom: 5px solid transparent;
      position: absolute;
      right: -4px;
      top: 6px;
      z-index: 999;
    }

    .form-img3 {
      // width: 100%;
      height: 54px;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;

      img {
        width: 54px;
        height: 100%;
      }
    }
  }
}
</style>
